<?php
use SimpleSoftwareIO\QrCode\BaconQrCodeGenerator;

class ControllerExtensionModuleDownloadApp extends Controller {

    /**
     * @return string
     * @throws Exception
     */
    public function index()
    {
        $this->load->language('extension/module/download_app');

        /** @var ModelSettingSetting $modelSetting */
        $modelSetting = $this->loadModel('setting/setting');
        $setting = $modelSetting->getSetting('module_download_app');

        if (! empty($setting['module_download_app_status'])) {
            $icon_url = image_resize($setting['module_download_app_icon']);
            $download_url = $this->url->link('extension/module/download_app/detectDevice');

            $data = [
                'qr_code'      => $this->loadQrCodeImageUrl($download_url, $icon_url),
                'download_url' => $download_url,
                'icon_url'     => $icon_url,
            ];

            return $this->load->view('extension/module/download_app', $data);
        } else{
            return '';
        }
	}

    /**
     * 检查设备
     */
	public function detectDevice()
    {
        $this->load->language('extension/module/download_app');
        $this->load->model('setting/setting');
        $setting = $this->model_setting_setting->getSetting('module_download_app');
        $data['android_url'] = $setting['module_download_app_android_url'];
        $data['ios_url'] = $setting['module_download_app_ios_url'];
        $data['module_status'] = $setting['module_download_app_status'];
        $this->response->setOutput($this->load->view('extension/module/download_app_detect', $data));
    }

    /**
     * 载入二维码地址
     *
     * @param $url
     * @param $image_url
     *
     * @return string
     */
    private function loadQrCodeImageUrl($url, $image_url)
    {
        $qrcode = new BaconQrCodeGenerator;
//        $image_content_string = file_get_contents($image_url, false, $this->streamContextNoSSLVerify());
        $image = $qrcode
            ->format('png')
            ->size(200)
            ->errorCorrection('H')
            ->margin(0)
//            ->mergeString($image_content_string, 0.3)
            ->generate($url);
        return 'data:image/png;base64, '. base64_encode($image);
    }

    /**
     * @return resource
     */
    private function streamContextNoSSLVerify()
    {
        return stream_context_create([
            "ssl" => [
                "verify_peer"      => false,
                "verify_peer_name" => false,
            ]
        ]);
    }
}
